<template>
  <div class="layer-control">
    <el-card class="layer-panel">
      <template #header>
        <div class="card-header">
          <span>图层控制</span>
        </div>
      </template>
      <el-tree
        :data="layerTree"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkedKeys"
        @check="handleLayerCheck"
      >
        <template #default="{ node, data }">
          <div class="layer-item">
            <span class="layer-title" :title="data.title">{{ data.title }}</span>
            <el-slider
              v-if="data.layer"
              v-model="data.opacity"
              :min="0"
              :max="1"
              :step="0.1"
              style="width: 80px"
              @change="(value) => handleOpacityChange(data.layer, value)"
            />
          </div>
        </template>
      </el-tree>
    </el-card>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'

const props = defineProps({
  layers: {
    type: Array,
    required: true
  },
  map: {
    type: Object,
    required: true
  }
})

const layerTree = ref([])
const checkedKeys = ref([])

// 初始化图层树
const initLayerTree = () => {
  if (props.layers.length > 0) {
    layerTree.value = props.layers.map((layer, index) => ({
      id: index.toString(),
      title: layer.get('title') || (layer.get('layerName') == "ol-plot-vector-layer"?'标绘图层': '未命名'),
      layer: layer,
      opacity: layer.getOpacity()
    }))

    // 设置默认选中的图层
    checkedKeys.value = layerTree.value
      .filter(item => item.layer.getVisible())
      .map(item => item.id)
  }
}

// 处理图层可见性变更
const handleLayerCheck = (data, checked) => {
  const { checkedKeys } = checked
  layerTree.value.forEach((item) => {
    if (item.layer) {
      item.layer.setVisible(checkedKeys.includes(item.id))
    }
  })
}

// 处理透明度变更
const handleOpacityChange = (layer, value) => {
  layer.setOpacity(value)
}

// 监听图层数组变化
watch(() => props.layers, () => {
  initLayerTree()
}, { deep: true })

onMounted(() => {
  initLayerTree()
})
</script>

<style lang="scss" scoped>
.layer-control {
  margin-left: vw(10);
}

.layer-panel {
  width: vw(280);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.layer-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding-right: vw(10);
}

.layer-title {
  flex: 1;
  max-width: vw(80);  // 限制宽度
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: vw(14);
  margin-right: vw(10);
}

:deep(.el-tree-node__content) {
  height: auto;
  padding: vw(8) 0;
}

:deep(.el-slider) {
  margin-left: vw(10);
}
</style> 